package com.qk.management.web.filter;

import cn.hutool.core.util.ObjectUtil;
import com.qk.common.util.jwtUtil.JwtUtils;
import com.qk.management.service.UserService;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
@Slf4j
//@WebFilter("/*")
public class LoginFilter implements Filter {


    private static final String LOGIN_PATH = "/login";
    private static final String TOKEN_HEADER_NAME = "token";
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String path = request.getServletPath();
        log.info("请求路径：{}", path);
        boolean isLoginPath = ObjectUtil.equals(path, LOGIN_PATH);
        if(isLoginPath){
            chain.doFilter(request, response);
            return;
        }
        String token = request.getHeader(TOKEN_HEADER_NAME);
        if(ObjectUtil.isEmpty( token)){
            response.setStatus(401);
            return;
        }
        try{
            Claims claims = JwtUtils.parseToken(token);
            //获取用户信息 TODO
            String username = claims.get("username", String.class);
            log.info("用户信息：{}", username);
            Object id = claims.get("id");
            log.info("用户id：{}", id);
            chain.doFilter(request, response);
        } catch (Exception e) {
            log.error("token解析失败", e);
            response.setStatus(401);
            return;
        }
    }
}
